<template>
  <div class="profile-basic-form">
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="100px"
      size="large"
      @submit.prevent="handleSubmit"
    >
      <!-- 昵称 -->
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="form.nickName"
          placeholder="请输入昵称（1-50个字符）"
          clearable
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="form.email"
          placeholder="请输入邮箱地址"
          clearable
          type="email"
        />
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item label="手机号" prop="phonenumber">
        <el-input
          v-model="form.phonenumber"
          placeholder="请输入手机号"
          clearable
          maxlength="11"
        />
      </el-form-item>

      <!-- 性别 -->
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio :value="'0'">男</el-radio>
          <el-radio :value="'1'">女</el-radio>
          <el-radio :value="'2'">保密</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 个性签名 -->
      <el-form-item label="个性签名" prop="signature">
        <el-input
          v-model="form.signature"
          type="textarea"
          :rows="3"
          placeholder="请输入个性签名（最多200个字符）"
          clearable
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          class="submit-btn"
          @click="handleSubmit"
        >
          保存修改
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, type FormInstance, type FormRules } from "vue";
import { ElMessage } from "element-plus";
import {
  updateUserProfileApi,
  validateNickName,
  validateEmail,
  validatePhoneNumber,
  formatErrorMessage,
  type UserProfile,
  type UpdateProfileRequest
} from "@/api/user-profile-update";

interface Props {
  userProfile: UserProfile | null;
}

interface Emits {
  (e: "success"): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 表单引用
const formRef = ref<FormInstance>();

// 表单数据
const form = reactive<UpdateProfileRequest>({
  nickName: "",
  email: "",
  phonenumber: "",
  sex: "2",
  signature: ""
});

// 加载状态
const loading = ref(false);

// 表单验证规则
const formRules: FormRules = {
  nickName: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!validateNickName(value)) {
          callback(new Error("昵称长度应为1-50个字符"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  email: [
    { required: true, message: "请输入邮箱地址", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!validateEmail(value)) {
          callback(new Error("邮箱格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  phonenumber: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (!validatePhoneNumber(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }]
};

// 监听用户信息变化，更新表单数据
watch(
  () => props.userProfile,
  newProfile => {
    if (newProfile) {
      form.nickName = newProfile.nickName || "";
      form.email = newProfile.email || "";
      form.phonenumber = newProfile.phonenumber || "";
      form.sex = newProfile.sex || "2";
      form.signature = newProfile.signature || "";
    }
  },
  { immediate: true }
);

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    loading.value = true;

    // 调用API更新信息
    const response = await updateUserProfileApi(form);

    if (response.code === 200) {
      ElMessage.success("个人信息更新成功");
      emit("success");
    } else {
      ElMessage.error(response.message || "更新失败");
    }
  } catch (error) {
    console.error("更新个人信息失败:", error);
    ElMessage.error(formatErrorMessage(error));
  } finally {
    loading.value = false;
  }
};

// 重置表单
const handleReset = () => {
  if (props.userProfile) {
    form.nickName = props.userProfile.nickName || "";
    form.email = props.userProfile.email || "";
    form.phonenumber = props.userProfile.phonenumber || "";
    form.sex = props.userProfile.sex || "2";
    form.signature = props.userProfile.signature || "";
  }

  // 清除验证状态
  formRef.value?.clearValidate();
};
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 768px) {
  .profile-basic-form {
    .el-form {
      :deep(.el-form-item__label) {
        width: 80px !important;
      }
    }
  }
}

.profile-basic-form {
  max-width: 600px;

  .el-form {
    .el-form-item {
      margin-bottom: 24px;

      :deep(.el-form-item__label) {
        font-weight: 500;
        color: #374151;
      }

      :deep(.el-input__wrapper) {
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          box-shadow: 0 0 0 1px #409eff;
        }

        &.is-focus {
          box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
        }
      }

      :deep(.el-radio-group) {
        .el-radio {
          margin-right: 24px;

          .el-radio__label {
            font-weight: 500;
          }
        }
      }
    }

    .submit-btn {
      padding: 12px 32px;
      font-weight: 600;
      background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
      border: none;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 8px 16px rgb(64 158 255 / 30%);
        transform: translateY(-2px);
      }

      &:active {
        transform: translateY(0);
      }

      &.is-loading {
        box-shadow: none;
        transform: none;
      }
    }
  }
}
</style>
